<?php
/**
 * Created by PhpStorm.
 * User: 徐剑锋
 * Date: 2016/5/28
 * Time: 21:47
 */

namespace work;

use app\ctr;
use C\lib\Db;

use C\mod\finance;
use C\mod\finance_details;
use C\mod\orderPiece;
use C\mod\pieceProblem;
use C\mod\pieceState;

class couriers extends base{


    public function clist($sql='' , $type=1) {

        if( $sql !== '') {

            if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

                if (isset($post['lastId'])) {
                    $lastId = $post['lastId'] + 0;
                    $lastId = $lastId <= 0 ? 0 : $lastId;
                } else {
                    $lastId = 0;
                }

                if($lastId == 0) $sqlLimit = ' cdo.id > 0 ';
                else  $sqlLimit = ' cdo.id < '.$lastId;

                $type == 2 ? $sField = 'cdo.piece_code pieceCode ,': $sField = '';;

                $stmt = Db::query('SELECT type FROM ' . DB_PRE . 'worker_type WHERE worker_id ="'.$worker->id .'" AND type = 0');
                if($stmt && $stmt->rowCount() > 0 ) {
                    $sqlAll = 'SELECT cdo.id id , cdo.order_id orderId ,'.$sField.' cdo.name_sender nameSender , cdo.address_sender addressSender , cdo.address_recipient addressRecipient , cdo.phone_sender phoneSender , cdo.time_add timeAdd , if(isNull(cda.code),"",cda.code) areaCode FROM   cd_order_piece cdo LEFT JOIN cd_area cda ON cda.id=cdo.area_id_recipient  WHERE cdo.worker_id='.$worker->id .'   AND '.$sql .' AND '. $sqlLimit.' ORDER BY id DESC LIMIT  10 ';

                    // 为收派员，显示其所在区域的状态为０的待收件
                    $stmt2 = Db::query($sqlAll);
                    $jPieces = [];

                    if($stmt2 && $stmt2->rowCount() > 0 ) {
                        date_default_timezone_set('PRC');
                        while ($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                            $data['timeAdd'] = date('Y-m-d H:i:s' , $data['timeAdd']);
                            $jPieces[] = $data;
                        }
                    }
                    $this->writeAesJson( 1 , ['jPieces'=> $jPieces] , 1);
                } else
                    $this->writeAesJson( 0 , '非收派员' ,1 );
            }
        } else
            $this->writeAesJson( 0 , '空查询', 1);
    }


    // --- 收派员收件 ---
    public function doSend() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="'.$worker->id .'" AND type = 0');
            if( $stmt->rowCount() > 0 ) {

                if(isset($post['pieceCode']) && trim($post['pieceCode']) != '') {
                    if(strtolower($post['pieceCode'][0]) == 'p') {

                        $stmt = Db::query('SELECT id FROM ' .DB_PRE. 'order_piece WHERE piece_code ="' . $post['pieceCode'] . '"');
                        if($stmt->rowCount() <= 0) {

                            if(isset($post['pieceId']) && $post['pieceId'] != '') {
                                Db::beginTransaction();
                                $pre = Db::prepare('UPDATE ' . DB_PRE . 'order_piece SET state = 1 , state_in =2 , piece_code =:piece_code ,worker_id=:worker_id where id= :id and state_in=1 and state=0');

                                if($pre->execute([':id' => $post['pieceId'], ':piece_code' => $post['pieceCode'], ':worker_id' => $worker->id])) {
                                    if($pre->rowCount() > 0) {
                                        // 添加关联表数据
                                        $pieceState = new \C\mod\pieceState();

                                        $pieceState->set([
                                            'worker_id' => $worker->id,
                                            'piece_id' => $post['pieceId'],
                                            'state_in' => 2, //  已取件
                                            'state' => 1,     // 运送中
                                            'user_show' => 1, // 用户不可见
                                            'time_add' => $_SERVER['REQUEST_TIME']
                                        ]);

                                        $k = 0;
                                        do {
                                            if(++$k > 3) {
                                                break;
                                            }   // 3次失败机会
                                        } while(!$pieceState->create());

                                        if($k <= 3) {
                                            Db::commit();
                                            $this->writeAesJson(1, [], 1);// 收件成功　　　　
                                        } else {
                                            Db::rollBack();
                                            $this->writeAesJson(0, '数据库关联添加失败', 1);
                                        }
                                    } else
                                        $this->writeAesJson(0, '修改失败或已修改该件状态', 1);
                                } else
                                    $this->writeAesJson(0, '无此未收件状态ID', 1);
                            } else
                                $this->writeAesJson(0, '件ID接收错误', 1);
                        } else
                            $this->writeAesJson(0, '件码已在使用中,请更换', 1);
                    } else
                        $this->writeAesJson(0, '件码格式不符合要求', 1);
                } else
                    $this->writeAesJson(0 ,'件号接收错误', 1);
            } else
                $this->writeAesJson( 0 , '非收派员', 1);
        }
    }


    // --- 收派员待确认收件列表 ---
    public function waitLists() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $worker = $this->getLogWorker();
            if (isset($post['lastId'])) {
                $lastId = $post['lastId'] + 0;
                $lastId = $lastId <= 0 ? 0 : $lastId;
            } else {
                $lastId = 0;
            }

            if($lastId == 0) $sqlLimit = ' cdo.id > 0 ';
            else  $sqlLimit = ' cdo.id > '.$lastId;

            $stmt = Db::query('SELECT type FROM ' . DB_PRE . 'worker_type WHERE worker_id ="'.$worker->id .'" AND type = 0');

            if($stmt && $stmt->rowCount() > 0 ) {

                $sqlAll = 'select distinct(cdo.id) id ,cdo.area_id_sender area_id_sender ,  cdo.order_id orderId , cdo.name_sender nameSender , cdo.phone_sender phoneSender , cdo.address_sender addressSender ,cdo.time_add timeAdd from cd_worker cdw , cd_order_piece cdo ,cd_area_worker cda where cdw.city_id=cdo.city_id_sender and cdw.id='.$worker->id .'  AND  ((cda.worker_id=cdw.id AND cda.id=cdo.area_id_sender) OR cdo.area_id_sender=0) and  cdo.state=0 and cdo.state_in=0   AND '. $sqlLimit.' ORDER BY id ASC LIMIT 10 ';

                // 为收派员，显示其所在区域的状态为０的待收件
                $stmt2 = Db::query($sqlAll);
                $jPieces = [];

                if($stmt2 && $stmt2->rowCount() > 0 ) {
                    date_default_timezone_set('PRC');
                    while ($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                        $data['timeAdd'] = date('Y-m-d H:i:s' , $data['timeAdd']);
                        $jPieces[] = $data;
                    }
                }
                $this->writeAesJson( 1 , ['jPieces'=> $jPieces] , 1);
            } else
                $this->writeAesJson( 0 , '非收派员' ,1 );

        }
    }

    // --- 收派员已接单列表,准备去收件 ---
    public function sureReceiveLists() {

        couriers::clist('cdo.state=0 and cdo.state_in=1' , 1);
    }


    // --- 收派员已收件列表 ---
    public function ReceivedLists() {

        couriers::clist('cdo.state=1 and cdo.state_in=2' , 2);
    }

    // --- 收派员派件列表 ---
    public function DeliveryLists() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $worker = $this->getLogWorker();
            if (isset($post['lastId'])) {
                $lastId = $post['lastId'] + 0;
                $lastId = $lastId <= 0 ? 0 : $lastId;
            } else {
                $lastId = 0;
            }

            if($lastId == 0) $sqlLimit = ' cdo.id > 0 ';
            else  $sqlLimit = ' cdo.id < '.$lastId;

            $stmt = Db::query('SELECT type FROM ' . DB_PRE . 'worker_type WHERE worker_id ="'.$worker->id .'" AND type = 0');

            if($stmt && $stmt->rowCount() > 0 ) {

                $sqlAll = 'SELECT cdo.id id , cdo.order_id orderId, cdo.piece_code pieceCode , cdo.name_sender nameSender , verify , cdo.address_recipient addressRecipient , cdo.phone_recipient phoneRecipient , cdo.time_add timeAdd FROM   cd_order_piece cdo WHERE cdo.worker_id='.$worker->id .' AND  cdo.state=1 AND cdo.state_in=10 AND '. $sqlLimit.' ORDER BY id DESC LIMIT  10 ';

                $stmt2 = Db::query($sqlAll);
                $jPieces = [];

                if($stmt2 && $stmt2->rowCount() > 0 ) {
                    date_default_timezone_set('PRC');
                    while ($data = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                        $data['verify'] = $data['verify'] ? 1 : 0;
                        $data['timeAdd'] = date('Y-m-d H:i:s' , $data['timeAdd']);
                        $jPieces[] = $data;
                    }
                }
                $this->writeAesJson( 1 , ['jPieces'=> $jPieces] , 1);
            } else
                $this->writeAesJson( 0 , '非收派员' ,1 );
        }

    }



    // --- 收派员扫码取件,即将送到客人手中---
    public function scanReceive() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $post['pieceCodes'] = (isset($post['pieceCodes'] )?  array_filter($post['pieceCodes']):[]);

            if(isset($post['pieceCodes']) && count($post['pieceCodes'])) {

                $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type = 0');
                if($stmt->rowCount() > 0) {

                    try {
                        $strTmp = '"' . implode('","', $post['pieceCodes']) . '"';
                        $stmt1 = Db::query('SELECT id FROM cd_order_piece WHERE  piece_code IN ('.$strTmp.') ');
                        $pieceIds = [];
                        while($data = $stmt1->fetch(\PDO::FETCH_ASSOC)) $pieceIds[] = $data['id'];

                        if ( $stmt1 && $stmt1->rowCount() > 0 ) {
                            Db::beginTransaction();

                            // 检查是否  站点1->分拨中心->站点2->收派员 ; 是,2收1费用
                            $stmt1 = Db::query('SELECT id, worker_id, piece_id  FROM cd_piece_state WHERE state_in in(3,9) AND  piece_id IN ('.implode(',',$pieceIds).') order by  piece_id desc,time_add desc ');

                            if ( $stmt1 && $stmt1->rowCount() > 0 ) {
                                $datas = [];
                                while($tmpData = $stmt1->fetch(\PDO::FETCH_ASSOC)) {
                                    $datas[$tmpData['piece_id']][] = $tmpData['worker_id'];
                                }

                                $point1 = [];
                                $point2 = [];
                                $p1ToP2 = [];
                                $p1ToP2PieceIds = [];

                                foreach($datas as $k => $v) {

                                    if(is_array($v)) {
                                        if(($len = count($v)) < 3) continue;
                                        if($v[0] == $v[$len-1] || in_array($v[0] , static::$centerPoint) || in_array($v[$len-1] , static::$centerPoint) ) continue;

                                        if(count(array_intersect($v, static::$centerPoint))) {
                                            isset($point1[$v[$len-1]]) ? --$point1[$v[$len-1]] : $point1[$v[$len-1]] = -1;   // ---
                                            isset($point2[$v[0]]) ? ++$point2[$v[0]] : $point2[$v[0]] = 1;   // +++

                                            if(!isset($p1ToP2[$v[$len-1]])) $p1ToP2[$v[$len-1]] = $v[0];

                                            if(isset($p1ToP2PieceIds[$v[0]][$v[$len-1]])) {
                                                $p1ToP2PieceIds[$v[0]][$v[$len-1]] .= ',' . $k;
                                            } else
                                                $p1ToP2PieceIds[$v[0]][$v[$len-1]] = $k;
                                        }
                                    }

//                                    if(is_array($v)) {
//                                        if(count($v) < 3) continue;
//                                        $i = 0;
//                                        while(isset($v[$i])) {
//                                            if(in_array($v[$i] , static::$centerPoint)) {
//                                                if(isset($v[$i - 1]) && !in_array($v[$i - 1] , static::$centerPoint) && isset($v[$i + 1]) && !in_array($v[$i + 1] , static::$centerPoint)) {
//                                                    if( $v[$i-1] == $v[$i + 1] ) break;
//                                                    isset($point1[$v[$i + 1]]) ? --$point1[$v[$i + 1]] : $point1[$v[$i + 1]] = -1;   // ---
//
//                                                    if(isset($point2[$v[$i - 1]])) {
//                                                        ++$point2[$v[$i - 1]];
//
//                                                    } else {
//                                                        $point2[$v[$i - 1]] = 1; // +++
//
//                                                    }
//                                                    if(!isset($p1ToP2[$v[$i + 1]])) $p1ToP2[$v[$i + 1]] = $v[$i - 1];
//
//
//                                                    if(isset($p1ToP2PieceIds[$v[$i - 1]][$v[$i + 1]])) {
//                                                        $p1ToP2PieceIds[$v[$i - 1]][$v[$i + 1]] .= ',' . $k;
//                                                    } else
//                                                        $p1ToP2PieceIds[$v[$i - 1]][$v[$i + 1]] = $k;
//                                                    break;
//                                                }
//                                            }
//                                            ++$i;
//                                        }
//                                    }
                                }

                                if(count($point2) != 1 || abs(array_sum($point1)) != array_sum($point2)) {
                                    $this->writeAesJson(0, '中心没扫描。或有不同站点的件，且一次只能收同一站点的件', 1);
                                    return false;
                                }

                                if(array_sum($point2) != count($post['pieceCodes'])) {
                                    $parr = [];
                                    foreach($p1ToP2PieceIds as $v) {
                                        foreach($v as $v2) $parr = array_merge($parr, explode(',', $v2));
                                    }
                                    $parr2 = array_diff($pieceIds, $parr);

                                    $stmt1 = Db::query('SELECT piece_code FROM cd_order_piece WHERE  id IN (' . implode(',', $parr2) . ') ');
                                    $pcodes = [];
                                    while($data = $stmt1->fetch(\PDO::FETCH_ASSOC)) $pcodes[] = $data['piece_code'];

                                    $this->writeAesJson(0, '未经中心扫描件码：' . implode(',', $pcodes), 1);
                                    return false;
                                }
                            }


                            // --- 派件员取件 ---
                            $stmt = Db::prepare('UPDATE ' . DB_PRE . 'order_piece SET state_in=10 ,worker_id=:worker_id WHERE (state_in >1 and state_in<=9) and state=1 and piece_code  IN ('.$strTmp.') ');
                            if( $stmt->execute([':worker_id'=> $worker->id]) && $stmt->rowCount() > 0) {
                                // 添加关联表数据
                                foreach($pieceIds as $v)
                                    $pieceStates [] = [
                                        'worker_id' => $worker->id,
                                        'piece_id' => $v,
                                        'state_in' => 10, // 派件员从站点取包，此时为待派送　10
                                        'state' => 1 ,
                                        'user_show' => 1, // 用户不可见
                                        'time_add' => $_SERVER['REQUEST_TIME']
                                    ];

                                $keyArr = array_keys($pieceStates[0]);

                                $pieceState = new \C\mod\pieceState();
                                $k = 0;
                                do {
                                    if(++$k > 3)  break;  // 3次失败机会
                                } while(!$pieceState->insert($keyArr, $pieceStates));

                                if($k <= 3) {

                                    if(count($point1)) {

                                        //  --- 添加 cd_finance_detail 表 ---
                                        $fdetail = [];
                                        foreach($point1 as $k => $v) {

                                            if(in_array($p1ToP2[$k], static::$special_points)) {
                                                $tmpPrice = static::$unit_price2;
                                            }else if($p1ToP2[$k] == static::$leiniao35_id) {
                                                $tmpPrice = static::$leiniao35;
                                            }else if($p1ToP2[$k] == static::$leiniao7_id) {
                                                $tmpPrice = static::$leiniao7;
                                            }else
                                                $tmpPrice = static::$unit_price;

                                            $t = $p1ToP2[$k];

                                            $fdetail[] = [
                                                'worker_id' => $k,
                                                'scan_type' => 3,
                                                'pay_type' => 1, // 1是负
                                                'price' => bcmul($v , $tmpPrice , 1),
                                                'piece_count'=>abs($v),
                                                'piece_ids'=>$p1ToP2PieceIds[$t][$k],
                                                'time_add' => $_SERVER['REQUEST_TIME'],
                                                'status' => 1 ,// 正常
                                                'worked_id'=>$p1ToP2[$k]
                                            ];
                                        }
                                        foreach($point2 as $k => $v) {
                                            if(in_array($k, static::$special_points)) {
                                                $tmpPrice = static::$unit_price2;
                                            }else if($k == static::$leiniao35_id) {
                                                $tmpPrice = static::$leiniao35;
                                            }else if($k == static::$leiniao7_id) {
                                                $tmpPrice = static::$leiniao7;
                                            }else
                                                $tmpPrice = static::$unit_price;

                                            $fdetail[] = [
                                                'worker_id' => $k,
                                                'scan_type' => 2,
                                                'pay_type' => 0, // 1是负
                                                'price' => bcmul($v , $tmpPrice , 1),
                                                'piece_count'=>$v,
                                                'piece_ids'=>implode(',',$p1ToP2PieceIds[$k]),
                                                'time_add' => $_SERVER['REQUEST_TIME'],
                                                'status' => 1 ,// 正常
                                                'worked_id'=>implode(',',array_keys($p1ToP2))
                                            ];
                                        }
                                        $keyArr = array_keys($fdetail[0]);
                                        $financeDetail = new \C\mod\finance_details();
                                        $k = 0;
                                        do {
                                            if(++$k > 3) break;  // 3次失败机会
                                        } while(!($tt = $financeDetail->insert($keyArr, $fdetail)));

                                        if($k <= 3) {

                                            // --- 更新 cd_finance 表 ---
                                            $sql = "UPDATE cd_finance SET balance = balance + CASE worker_id ";
                                            $time_sql = '';
                                            $datesArr = [];

                                            foreach($point1 as $k => $v) {
                                                $sql .= ' WHEN :id' . $k . ' THEN :price' . $k;
                                                $time_sql .= ' WHEN :id' . $k . ' THEN ' . $_SERVER['REQUEST_TIME'];
                                                if(in_array($p1ToP2[$k], static::$special_points)) {
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$unit_price2,1)]);
                                                }else if($p1ToP2[$k] == static::$leiniao35_id) {
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$leiniao35,1)]);
                                                }else if($p1ToP2[$k] == static::$leiniao7_id){
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$leiniao7,1)]);
                                                }else
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$unit_price,1)]);
                                            }

                                            foreach($point2 as $k => $v) {
                                                $sql .= ' WHEN :id' . $k . ' THEN :price' . $k;
                                                $time_sql .= ' WHEN :id' . $k . ' THEN ' . $_SERVER['REQUEST_TIME'];
                                                if(in_array($k, static::$special_points)) {
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$unit_price2,1)]);
                                                }else if($k == static::$leiniao35_id) {
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$leiniao35,1)]);
                                                }else if($k == static::$leiniao7_id) {
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$leiniao7,1)]);
                                                }else
                                                    $datesArr = array_merge($datesArr, [':id' . $k => $k, ':price' . $k => bcmul($v , static::$unit_price,1)]);
                                            }

                                            $workerids = array_unique(array_merge(array_keys($point1), array_keys($point2)));
                                            $sql .= ' END, time_update = CASE worker_id ' . $time_sql . '  END WHERE worker_id IN (' . implode(',', $workerids) . ')';
                                            $preFinance = Db::prepare($sql);
                                            unset($sql);

                                            if($preFinance->execute($datesArr) && ($row = $preFinance->rowCount()) == (count($workerids))) {
                                                Db::commit();
                                                unset($fdetail, $workerids, $datesArr, $point1, $point2);
                                                $this->writeAesJson(1, [] ,1);
                                            } else {
                                                \C\log('［分拨中心］财务信息更新失败,站2收站1   \n workerids='.implode(',', $workerids). '  \n datas='.implode(' , ', $datesArr));
                                                Db::rollBack();
                                                $this->writeAesJson(0, '财务信息更新失败', 1);
                                                return false;
                                            }
                                            //  --- /添加 cd_finance_detail 表 ---
                                        } else {
                                            Db::rollBack();
                                            $workerids = array_unique(array_merge(array_keys($point1), array_keys($point2)));
                                            $f = '';
                                            foreach($fdetail as $v) {
                                                $f .='('. implode(',', $v).')';
                                            }
                                            \C\log('［分拨中心］财务路由添加失败,站2收站1   \n workerids='.implode(',', $workerids).'  \n datas='.$f);
                                            $this->writeAesJson(0, '财务路由添加失败', 1);
                                            return false;
                                        }

                                    }


                                } else {
                                    Db::rollBack();
                                    $this->writeAesJson(0, '数据库关联添加失败', 1);
                                }
                            } else
                                throw new \Exception('更新件状态失败或已更新过了');
                        } else
                            $this->writeAesJson(0 , '查询件信息失败', 1);
                    } catch(\Exception $e) {
                        Db::rollBack(); // 执行失败，事务回滚
                        $this->writeAesJson(0, '操作库失败,' . $e->getMessage() , 1);
                    }

                } else
                    $this->writeAesJson(0, '非收派员', 1);
            }else
                $this->writeAesJson(0, '件号不能为空', 1);
        }
    }

    // --- 派件员确认派件返回是否为到付 ---
    public function receiveVerifyTP() {
        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($post['pieceId']) && $post['pieceId'] != '') {
                if ($piece = orderPiece::get(['id' => $post['pieceId']])) {
                    $this->writeAesJson(1, [
                        'price' =>$piece->price,
                        'type' => $piece->type_pay
                    ], 1);
                } else
                    $this->writeAesJson(0, '获取该件信息失败', 1);
            } else
                $this->writeAesJson(0, '件ID接收不能为空', 1);
        }
    }

    // --- 派件员提交问题单 ---
    public function problem() {
        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($post['pieceId']) && $post['pieceId'] != '') {
                if (isset($post['pieceCode']) && $post['pieceCode'] != '') {
                    if (isset($post['usual']) || isset($post['other'])) {
                        if ($piece = orderPiece::get(['id' => $post['pieceId']])) {
                            $siteid=[3,9];
                            if ($pieceStates = pieceState::getlist([['state_in', 'in', $siteid],['worker_id', '!=', 8],['state_in', '!=', 179], 'piece_id' => $post['pieceId']], [0, 1], ['id', 'DESC'])) {
                                foreach($pieceStates as $pieceState) {
                                    $siteId = $pieceState->worker_id;
                                }
                                $pieceProblem = new pieceProblem();
                                $pieceProblem->set([
                                    'worker_id' => $worker->id,
                                    'site_id' => $siteId,
                                    'status' => 0,
                                    'usual' => $post['usual'],
                                    'other' => $post['other'],
                                    'piece_code' => trim($post['pieceCode']),
                                    'piece_id' => $piece->id,
                                    'time_add' => $_SERVER['REQUEST_TIME']
                                ]);
                                if ($pieceProblem->create()) {
                                    $piece->set([
                                        'state' => 4,
                                        'state_in' => 13,
                                        'worker_id' => $worker->id
                                    ]);
                                    $piece->update();
                                    $pieceState = new pieceState();
                                    $pieceState->set([
                                        'worker_id' => $worker->id,
                                        'state' => 4,
                                        'state_in' => 13,
                                        'piece_id' => $post['pieceId'],
                                        'time_add' => $_SERVER['REQUEST_TIME']
                                    ]);
                                    $pieceState->create();
                                    $this->writeAesJson(1, 1);
                                } else
                                    $this->writeAesJson(0, '请重新提交', 1);
                            } else
                                $this->writeAesJson(0, '找不到该件派出的站点', 1);
                        } else
                            $this->writeAesJson(0, '此件不存在', 1);
                    } else
                        $this->writeAesJson(0, '请提交问题', 1);
                }else
                    $this->writeAesJson(0, '请提交件号', 1);
            } else
                $this->writeAesJson(0, '件ID接收不能为空', 1);
        }
    }


    // --- 站点问题件 ---
    public function siteProblems() {
        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($_POST['lastId']) && trim($_POST['lastId']) != '') {
                $lastId = trim($_POST['lastId'] + 0);
            } else {
                $lastId = 0;
            }
            if($post['lastId'] == 0) {
                $lastId = ['id','>',$lastId];
            } else {
                $lastId = ['id','<',$lastId];
            }
            $list = [];
            if($problems = pieceProblem::getList(['site_id' => $worker->id, 'status' => 0, $lastId],[0, 10], ['id', 'DESC'])) {
                foreach($problems as $problem) {
                    $list[] = [
                        'pieceCode' => $problem->piece_code,
                        'id' => $problem->id,
                        'pieceId' => $problem->piece_id,
                        'usual' => $problem->usual,
                        'other' => $problem->other
                    ];
                }
            }
            $this->writeAesJson(1, [
                'list' => $list
            ], 1);
        }
    }

    // --- 其他站点问题件 ---
    public function otherSiteProblems() {
        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($_POST['lastId']) && trim($_POST['lastId']) != '') {
                $lastId = trim($_POST['lastId'] + 0);
            } else {
                $lastId = 0;
            }
            if($post['lastId'] == 0) {
                $lastId = ['id','>',$lastId];
            } else {
                $lastId = ['id','<',$lastId];
            }
            $list = [];
            if($problems = pieceProblem::getList([['site_id','!=',  $worker->id], 'status' => 0, $lastId],[0, 10], ['id', 'DESC'])) {
                foreach ($problems as $problem) {
                    $list[] = [
                        'pieceCode' => $problem->piece_code,
                        'id' => $problem->id,
                        'pieceId' => $problem->piece_id,
                        'usual' => $problem->usual,
                        'other' => $problem->other
                    ];
                }
            }
            $this->writeAesJson(1, [
                'list' => $list
            ], 1);
        }
    }

    // --- 解决问题 ---
    public function noProblem() {
        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($post['pieceId']) && $post['pieceId'] != '') {
                if($piece = orderPiece::get(['id' => $post['pieceId']])) {
                    $piece->set([
                        'state' => 3,
                        'state_in' => 11,
                        'worker_id' => $worker->id
                    ]);
                    if($piece->update()) {
                        if($problem = pieceProblem::get(['piece_id' => $post['pieceId'], 'status' => 0])) {
                            $problem->set([
                                'status' => 1,
                                'time_update' =>$_SERVER['REQUEST_TIME']
                            ]);
                            if($problem->update()) {
                                $pieceState = new pieceState();
                                $pieceState->set([
                                    'worker_id' => $worker->id,
                                    'state' => 3,
                                    'state_in' => 11,
                                    'piece_id' => $post['pieceId'],
                                    'time_add' => $_SERVER['REQUEST_TIME']
                                ]);
                                $pieceState->create();
                                $this->writeAesJson(1, 1);
                            } else
                                $this->writeAesJson(1, '解决问题失败请重新提交', 1);
                        } else
                            $this->writeAesJson(0, '该问题件不存在', 1);
                    }else
                        $this->writeAesJson(0, '出现错误请重新提交', 1);
                } else
                    $this->writeAesJson(0, '该件已不存在', 1);
            } else
                $this->writeAesJson(0, '件ID接收不能为空', 1);
        }
    }

    // --- 派件员确认派件成功 ---
    public function receiveVerify() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type = 0');

            if($stmt->rowCount() > 0) {

                if(isset($post['pieceId']) && $post['pieceId'] != '') {
                    if($piece = orderPiece::get(['id' => $post['pieceId']] )) {
                        if( (isset($post['verify']) && trim($piece->verify) != '' && trim($piece->verify) == trim($post['verify'])) || ( !isset($post['verify']) && isset($post['phone']) && (trim($post['phone']=='' || (trim($post['phone']) != ''  && trim($piece->phone_recipient) == trim($post['phone'])))))  ) {

                            $pieceP = $piece->price;
                           $siteid=[3,9];
                            if($piece->type_pay == 2) {
                                if ($sitea = pieceState::getList([['state_in', 'in', $siteid], ['worker_id', '!=', 8],['worker_id', '!=', 179],'piece_id' => $post['pieceId']], [1, 1], ['id', 'DESC'])) {
                                    foreach ($sitea as $site) {
                                        $workerId = $site->worker_id;
                                    }
                                    if ($siteb = pieceState::getList([['state_in', 'in', $siteid],['worker_id', '!=', 8],['worker_id', '!=', 179], 'piece_id' => $post['pieceId']], [0, 1], ['id', 'DESC'])) {
                                        foreach ($siteb as $site) {
                                            $workedId = $site->worker_id;
                                        }

                                        $financea = finance::get(['worker_id' => $workerId]);
                                        $financea->set([
                                            'balance' => $pieceP + $financea->balance
                                        ]);
                                        if ($financea->update()) {
                                            $financeb = finance::get(['worker_id' => $workedId]);
                                            $financeb->set([
                                                'balance' => $financeb->balance - $pieceP
                                            ]);
                                            if ($financeb->update()) {
                                                $financeda = new finance_details();
                                                $financeda->set([
                                                    'pay_type' => 0,
                                                    'worker_id' => $workerId,
                                                    'scan_type' => 5,
                                                    'price' => $pieceP,
                                                    'piece_count' => 1,
                                                    'piece_ids'=>$post['pieceId'],
                                                    'time_add' => $_SERVER['REQUEST_TIME'],
                                                    'worked_id' => $workedId
                                                ]);
                                                $financeda->create();
                                                $financedb = new finance_details();
                                                $financedb->set([
                                                    'pay_type' => 1,
                                                    'worker_id' => $workedId,
                                                    'scan_type' => 6,
                                                    'price' => -$pieceP,
                                                    'piece_count' => 1,
                                                    'piece_ids'=>$post['pieceId'],
                                                    'time_add' => $_SERVER['REQUEST_TIME'],
                                                    'worked_id' => $workerId
                                                ]);
                                                $financedb->create();

                                            } else
                                                $this->writeAesJson(0, '请求错误', 1);

                                        } else
                                            $this->writeAesJson(0, '请求错误1', 1);

                                    } else
                                        $this->writeAesJson(0, '找不到发出站点b', 1);

                                } else
                                    $this->writeAesJson(0, '找不到发出站点a', 1);

                            }

                            Db::beginTransaction();
                            $pre = Db::prepare('UPDATE '.DB_PRE . 'order_piece SET state=2 , state_in=11 ,worker_id=:worker_id  WHERE state=1 and state_in=10 and id= :id');
                            if($pre->execute([':id'=> $post['pieceId'] , ':worker_id'=> $worker->id] )) {
                                if($pre->rowCount() > 0) {// 添加关联表cd_piece_state数据
                                    $pieceState = new \C\mod\pieceState();

                                    $pieceState->set([
                                        'worker_id' => $worker->id,
                                        'piece_id' => $piece->id,
                                        'state_in' => 11, // 已送达
                                        'state' => 2,     // 已送达
                                        'user_show' => 1, // 用户不可见
                                        'time_add' => $_SERVER['REQUEST_TIME']
                                    ]);

                                    $k = 0;
                                    do {
                                        if(++$k > 3) break; // 3次失败机会
                                    } while(!$pieceState->create());

                                    if($k <= 3) {
                                        Db::commit();
                                        $this->writeAesJson(1 , [] , 1);
                                    } else {
                                        Db::rollBack();
                                        $this->writeAesJson(0, '数据库关联添加失败', 1);
                                    }
                                } else
                                    $this->writeAesJson(0 , '已修改该件为此状态', 1);
                            } else
                                $this->writeAesJson(0 ,'更改该件状态错误', 1);
                        } else
                            $this->writeAesJson(0 ,'验证错误', 1);
                    } else
                        $this->writeAesJson(0 ,'获取该件信息失败', 1);
                } else
                    $this->writeAesJson(0 ,'件ID接收不能为空', 1);
            } else
                $this->writeAesJson(0, '非收派员', 1);
        }
    }

    // --- 派件员确认接单
    public function sureReceive() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {

            $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type = 0');
            if($stmt->rowCount() > 0) {

                if(isset($post['pieceId']) && $post['pieceId'] != '') {
                    Db::beginTransaction();

                    $stmt = Db::prepare('UPDATE '.DB_PRE. 'order_piece SET state_in =1  ,worker_id=:worker_id   where state_in=0 and id= :id');
                    if( $stmt->execute(['id'=>$post['pieceId'] , ':worker_id'=> $worker->id]) &&  $stmt->rowCount() > 0  ){
                        //成功，在 cd_piece_state 中添加相信数据
                        $pieceState = new \C\mod\pieceState();

                        $pieceState->set([
                            'worker_id' => $worker->id,
                            'piece_id' => $post['pieceId'],
                            'state_in' => 1,  // 状态变为 待取件
                            'state' => 0,     // 还未取件，状态为待运中
                            'user_show' => 1, // 用户不可见
                            'time_add' => $_SERVER['REQUEST_TIME']]);

                        $k = 0;
                        do {
                            if(++$k > 3) break;// 3次失败机会
                        } while(!$pieceState->create());

                        if($k <= 3) {
                            Db::commit();
                            $this->writeAesJson(1, [] ,1);
                        } else {
                            Db::rollBack();
                            $this->writeAesJson(0, '数据库关联添加失败,接单失败', 1);
                        }
                    } else
                        $this->writeAesJson(0 ,'接单失败或已接此单了', 1);
                } else
                    $this->writeAesJson(0 ,'件ID接收不能为空', 1);
            } else
                $this->writeAesJson(0, '非收派员', 1);
        }
    }




    // --- 扫码返回其当前内容状态 , $flag=false表为ＡＰＰ使用，为true表为微信,PC使用 ---
    public function scanCode() {

        global $_STATE_IN_PIECE;

        if(!Db::isConnected()) Db::connect();

        if( (!isset($_POST['aes']) && isset($_POST['flag']) && $_POST['flag']=='1') || ( isset($_POST['aes']) &&  ($post = $this->getAesPost()) && ($worker = $this->getLogWorker()))) {

            $flag = isset($_POST['aes']) ?  false : true;

            if($flag) $post = $_POST;

            date_default_timezone_set('PRC');

            $post['scanCode'] = trim($post['scanCode']);
            if(preg_match('/\d{15}|P\d{15}|\d{9}|P\d{9}/i' , $post['scanCode'])) {

                $stmt = Db::query('SELECT cdo.id id ,if(isNull(cdw.realname),"",cdw.realname) workerName, cdw.phone workerPhone , cdo.piece_code pieceCode , cdo.address_sender addressSender ,cdo.address_recipient addressRecipient , cdo.phone_sender phoneSender ,cdo.phone_recipient phoneRecipient ,cdo.name_sender nameSender , cdo.name_recipient nameRecipient , cdo.time_add timeAdd , cdo.state_in stateIn , cdo.bag_id bag_id ,cdo.user_id user_id FROM cd_order_piece cdo  LEFT JOIN cd_worker cdw ON cdw.id=cdo.worker_id  WHERE piece_code ="' . $post['scanCode'] . '" limit 1');

                $jPiece =['id'=>'']; $jPieceStates = []; $platform =-1;
                if( $res = $stmt->fetch(\PDO::FETCH_ASSOC) ) {
                    $jPiece = $res;
                    unset($jPiece['bag_id']);
                    $jPiece['timeAdd'] = date('Y-m-d H:i:s', $jPiece['timeAdd']);
                    $jPiece['stateIn'] = isset($_STATE_IN_PIECE[$jPiece['stateIn']]) ? $_STATE_IN_PIECE[$jPiece['stateIn']] : '未知';

                    //发件人+收件人的手机号　是否为空吧，若为空，platform 为 ２的值，表是面单的．若存在返回 platform  为０　表线上的
                    $platform = $jPiece['phoneSender']=='' &&  $jPiece['phoneRecipient']=='' ? 2 : 0;

                    // --- 获取件的所有状态 ---

                    $stmt = Db::query('SELECT cdp.* , cdw.realname realname ,cdw.phone phone FROM cd_piece_state cdp , cd_worker cdw where cdp.worker_id=cdw.id and piece_id = '.$jPiece['id'] .' order by cdp.time_add ');

                    $i = 0;
                    $user = false;
                    $oldData = ['realname'=> '' ,'phone' =>''];
                    while($data = $stmt->fetch(\PDO::FETCH_ASSOC)) {

                        $jPieceStates[$i]['time_add'] = date('Y-m-d H:i:s',$data['time_add']);
                        switch ($data['state_in']) {
                            case '0':
                                $jPieceStates[$i]['content'] = '工作人员 '.$data['realname'].' 已接单';
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '1':
                                $jPieceStates[$i]['content'] = '工作人员 '.$data['realname'].' 准备出发取件';
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '2':
                                $jPieceStates[$i]['content'] = '工作人员 '.$data['realname'].' 已取件';
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '3': case '9':
                            if(isset($oldData['state_in']) && $oldData['state_in']=='3')
                                $jPieceStates[$i]['content'] = ' '.$oldData['realname'].' 转于 '.$data['realname'].' 收录';
                            else
                                $jPieceStates[$i]['content'] = (trim($oldData['realname']!='' || trim($oldData['phone'])!='')) ? '工作人员 '.$oldData['realname'].' 送到集散点, '.$data['realname'].' 收录' : ' '.$data['realname'].' 收录';

                            if(trim($oldData['realname']!='' || trim($oldData['phone'])!='')) {
                                $jPieceStates[$i]['realname'][0] = $oldData['realname'];
                                $jPieceStates[$i]['realname'][1] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $oldData['phone'];
                                $jPieceStates[$i]['phone'][1] = $data['phone'];
                            } else {
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                            }
                            break;
                            case '4': case '8':
                            $jPieceStates[$i]['content'] = '工作人员 '.$oldData['realname'].' 送达支线, '.$data['realname'].' 收录';
                            $jPieceStates[$i]['realname'][0] = $oldData['realname'];
                            $jPieceStates[$i]['realname'][1] = $data['realname'];
                            $jPieceStates[$i]['phone'][0] = $oldData['phone'];
                            $jPieceStates[$i]['phone'][1] = $data['phone'];
                            break;
                            case '5':
                                $bag = \C\mod\bag::get(['id'=>$res['bag_id']]);
                                $jPieceStates[$i]['content'] = '工作人员 '.$data['realname'].' 取得该件装包，包号：'.$bag->code;
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '6':
                                if(!$user) $user  = \C\mod\user::get(['id'=>$jPiece['user_id']]);
                                if($user) {
                                    $jPieceStates[$i]['content'] = '抢包人 '.$user->realname.' 取得该件并上众包';
                                    $jPieceStates[$i]['realname'][0] = $user->realname;
                                    $jPieceStates[$i]['phone'][0] = $user->phone;
                                }
                                break;
                            case '7':
                                if(!$user) $user = \C\mod\user::get(['id' => $jPiece['user_id']]);
                                if($user) {
                                    $jPieceStates[$i]['content'] = '抢包人 ' . $user->realname . ' 已下车';
                                    $jPieceStates[$i]['realname'][0] = $user->realname;
                                    $jPieceStates[$i]['phone'][0] = $user->phone;
                                }
                                break;
                            case '10':
                                $jPieceStates[$i]['content'] = '工作人员 '.$data['realname'].' 已取得该件准备派送';
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '11':
                                $jPieceStates[$i]['content'] = '该件由 '.$data['realname'].' 已送达';
                                $jPieceStates[$i]['realname'][0] = $data['realname'];
                                $jPieceStates[$i]['phone'][0] = $data['phone'];
                                break;
                            case '12':case '13':
                            $jPieceStates[$i]['content'] = '该件无效或问题件';break;
                            case '14':
                                $jPieceStates[$i]['content'] = '该件待付款';break;
                            case '15':
                                $stmt2 = Db::query('SELECT cdo.express_code expressCode , cde.name expressName ,cde.code code FROM cd_order_piece cdo, cd_express cde where cdo.express_id = cde.id AND cdo.piece_code="'. $post['scanCode'] .'" limit 1');
                                if($data2 = $stmt2->fetch(\PDO::FETCH_ASSOC)) {
                                    //                                        $jPieceStates[$i]['content'] = '工作人员 ' . $data['realname'] . ' 将此件转于' . $data2['expressName'] . '单号:' . $data2['expressCode'];
                                    //                                        $jPieceStates[$i]['realname'][0] = $data['realname'];
                                    //                                        $jPieceStates[$i]['phone'][0] = $data['phone'];

                                    if($data2['code']) {
                                        $url = 'http://www.kuaidi100.com/query?type='.trim($data2['code']).'&postid='.trim($data2['expressCode']).'&id=19&valicode=&temp='.mt_getrandmax();
                                        $express = json_decode(self::getExpressMsg($url) ,true);

                                        if(isset($express['data']) && ($express['message'] === 'ok')) {
                                            for($i, $e = count($express['data']) - 1; $e >= 0;) {
                                                $jPieceStates[$i]['time_add'] = $express['data'][$e]['time'];

                                                $jPieceStates[$i]['content'] = str_replace(['(点击查询电话)', ' '], ['', ''], $express['data'][$e]['context']);
                                                $jPieceStates[$i]['realname'][0] = '';
                                                $jPieceStates[$i]['phone'][0] = '';
                                                if(--$e >= 0) $i++;
                                            }
                                        }
                                    }
                                }



                                break;
                        }
                        $i++;
                        $oldData = $data;
                    }

                }
                $flag ?  $this->writeJson(1, ['type'=>1, 'platform'=>$platform , 'jPiece'=>$jPiece , 'jPieceStates'=>$jPieceStates]) : $this->writeAesJson(1, ['type'=>1 ,  'platform'=>$platform , 'jPiece'=>$jPiece , 'jPieceStates'=>$jPieceStates] ,1);

            }else if($post['scanCode'][0] == 'S') {
                $stmt  = Db::query('SELECT cds.code code , cds.time_add time_add , cds.count count , cdc.name name FROM cd_sack cds , cd_city cdc where cds.city_id=cdc.id and cds.code ="'.$post['scanCode'] . '"');

                $sack = ['code'=>''];
                if($sdata = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $sdata['time_add'] =  date('Y-m-d H:i:s',$sdata['time_add']);
                    $sack = $sdata;
                }

                $flag ? $this->writeJson(1, ['type'=> 2 , 'jSack'=>$sack]): $this->writeAesJson(1, ['type'=> 2 , 'jSack'=>$sack] ,1);

            }else if($post['scanCode'][0] == 'C') {

                $stmt  = Db::query('SELECT cdc.code code , cdc.time_add time_add , cdc.count count , if(isNull(cda.name),"未划分区域", name) name FROM cd_crate cdc LEFT JOIN cd_area cda ON cdc.area_id=cda.id WHERE cdc.code = "'.$post['scanCode'].'"');

                $crate = ['code'=>''];
                if($sdata = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $sdata['time_add'] =  date('Y-m-d H:i:s',$sdata['time_add']);
                    $crate = $sdata;
                }

                $flag ? $this->writeJson(1, ['type'=> 3 , 'jCrate'=>$crate]): $this->writeAesJson(1, ['type'=> 3 , 'jCrate'=>$crate] ,1);


            }else if($post['scanCode'][0] == 'B') {
                global $_STATE_BAG;
                $stmt  = Db::query('SELECT cdb.code code , cdb.time_add time_add , cdb.count count , cds.name site_sendName ,b.site_receiveName site_receiveName ,state FROM cd_bag cdb , cd_site cds ,(SELECT cds.name site_receiveName FROM cd_bag cdb , cd_site cds where cdb.site_receive=cds.id and code = "'.$post['scanCode'].'") b where cdb.site_send=cds.id and code = "'.$post['scanCode'].'"');


                $bag = ['code'=>''];
                if($bdata = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $bdata['state'] = $_STATE_BAG[$bdata['state']];
                    $bdata['time_add'] = date('Y-m-d H:i:s',$bdata['time_add']);
                    $bag = $bdata;
                }

                $flag ? $this->writeJson(1, ['type'=> 4 , 'jBag'=>$bag]):$this->writeAesJson(1, ['type'=> 4 , 'jBag'=>$bag] ,1);

            }else
                $flag ? $this->writeJson(0, '所扫码格式错误'): $this->writeAesJson(0, '所扫码格式错误', 1);
        }
    }

    public function transfer() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if(isset($post['code']) && ($post['code']=trim($post['code'])) != '') {
                if(isset($post['express_id']) && ($post['express_id']=trim($post['express_id'])) != '') {
                    if(isset($post['express_code']) && ($post['express_code']=trim($post['express_code'])) != '') {
                        Db::beginTransaction();
                        $stmt = Db::prepare('UPDATE '.DB_PRE. 'order_piece SET express_id =:expressId  , express_code=:expressCode ,worker_id=:workerId ,state=2,state_in=15 WHERE piece_code=:pieceCode AND state =1');
                        $stmt->execute([
                            ':expressId' => $post['express_id'],
                            ':expressCode' => $post['express_code'],
                            ':workerId' => $worker->id,
                            ':pieceCode' => $post['code']
                        ]);

                        if($stmt->rowCount()>0) {
                            $stmt = Db::query('SELECT id FROM cd_order_piece WHERE  piece_code ="'.$post['code'].'" limit 1');
                            if($stmt && $stmt->rowCount() >0) {

                                if($data = $stmt->fetch(\PDO::FETCH_ASSOC)) {

                                    $dates[] = [
                                        'worker_id' => $worker->id,
                                        'piece_id' => $data['id'],
                                        'state_in' => 15, // 表转运
                                        'state' => 2,
                                        'user_show' =>  0,
                                        'time_add' => $_SERVER['REQUEST_TIME']
                                    ];
                                    $keyArr = array_keys($dates[0]);

                                    $pieceState = new pieceState();
                                    $k = 0;

                                    do {
                                        if($k++ >= 3) break;   // 3次失败机会
                                    } while(!$pieceState->insert($keyArr, $dates));
                                    if($k <= 3) {
                                        Db::commit();
                                        $this->writeAesJson(1, [], 1);
                                    } else {
                                        Db::rollBack();
                                        $this->writeAesJson(0, '转件错误,件内部状态添加失败', 1);
                                    }
                                } else
                                    $this->writeAesJson(0 , '转件错误,获取件信息失败',1);
                            } else
                                $this->writeAesJson(0 , '查询快递件码错误，可能无此件码',1);
                        } else
                            $this->writeAesJson(0 , '转件错误,更新数据库失败或查无此件号',1);
                    } else
                        $this->writeAesJson(0 , '没有快递单号传入',1);
                } else
                    $this->writeAesJson(0 , '没有快递id传入',1);
            } else
                $this->writeAesJson(0 , '没有件号传入',1);
        }
    }



    // --- 　根据件码添加件 ---
    public  function addPiece() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if(isset($post['code']) && trim($post['code']) != '') {
                $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="'.$worker->id .'" AND type = 0');
                if( $stmt->rowCount() > 0 ) {
                    if(!\C\mod\orderPiece::get(['piece_code'=>trim($post['code'])])){
                        Db::beginTransaction();

                        $piece = new orderPiece();
                        $piece->set([
                            'piece_code'=>$post['code'],
                            'state_in'=> 2,
                            'state' => 1,
                            'worker_id'=>$worker->id ,
                            'time_add'=> $_SERVER['REQUEST_TIME']
                        ]);

                        if($piece->create()) {
                            $pieceState = new pieceState();
                            $pieceState->set([
                                'worker_id' => $worker->id,
                                'piece_id' => $piece->id,
                                'state_in' => 2,
                                'state' => 1,
                                'user_show' =>  1,
                                'time_add' => $_SERVER['REQUEST_TIME']
                            ]);

                            $k = 0;
                            do {
                                if($k++ >= 3) break;   // 3次失败机会
                            } while(!$pieceState->create());

                            if($k <= 3) {
                                Db::commit();
                                $this->writeAesJson(1, [], 1);
                            } else {
                                Db::rollBack();
                                $this->writeAesJson(0, '扫一扫收件错误,件内部状态添加失败', 1);
                            }
                        } else
                            $this->writeAesJson(0 , '添加数据库失败',1);
                    } else
                        $this->writeAesJson(0 , '此件码已存在',1);
                } else
                    $this->writeAesJson( 0 , '非收派员，无法收件' ,1 );
            } else
                $this->writeAesJson(0 , '没有件码传入',1);
        }
    }

    // --- 扫描到付 ---
    public  function addPieceTP() {

        if(($post = $this->getAesPost()) && ($worker = $this->getLogWorker())) {
            if (isset($post['code']) && trim($post['code']) != '') {
                if (isset($post['price']) && trim($post['price']) != '') {
                    $stmt = Db::query('SELECT TYPE FROM ' . DB_PRE . 'worker_type WHERE worker_id ="' . $worker->id . '" AND type = 0');
                    if ($stmt->rowCount() > 0) {
                        if (!\C\mod\orderPiece::get(['piece_code' => trim($post['code'])])) {
                            Db::beginTransaction();

                            $piece = new orderPiece();
                            $piece->set([
                                'piece_code' => $post['code'],
                                'state_in' => 2,
                                'state' => 1,
                                'worker_id' => $worker->id,
                                'type_pay' => 2,
                                'price' => $post['price'],
                                'time_add' => $_SERVER['REQUEST_TIME']
                            ]);

                            if ($piece->create()) {
                                $pieceState = new pieceState();
                                $pieceState->set([
                                    'worker_id' => $worker->id,
                                    'piece_id' => $piece->id,
                                    'state_in' => 2,
                                    'state' => 1,
                                    'user_show' => 1,
                                    'time_add' => $_SERVER['REQUEST_TIME']
                                ]);

                                $k = 0;
                                do {
                                    if ($k++ >= 3) break;   // 3次失败机会
                                } while (!$pieceState->create());

                                if ($k <= 3) {
                                    Db::commit();
                                    $this->writeAesJson(1, [], 1);
                                } else {
                                    Db::rollBack();
                                    $this->writeAesJson(0, '扫一扫收件错误,件内部状态添加失败', 1);
                                }
                            } else
                                $this->writeAesJson(0, '添加数据库失败', 1);
                        } else
                            $this->writeAesJson(0, '此件码已存在', 1);
                    } else
                        $this->writeAesJson(0, '非收派员，无法收件', 1);
                } else
                    $this->writeAesJson(0, '没有到付费用传入', 1);
            } else
                $this->writeAesJson(0, '没有件码传入', 1);
        }
    }

    public static function getExpressMsg($url , $options = array()) {
        $options[CURLOPT_RETURNTRANSFER] = true;
        $options[CURLOPT_TIMEOUT] = 5;
        $options[CURLOPT_REFERER] =  'http://www.kuaidi100.com/';
        $options[CURLOPT_USERAGENT] = 'www.kuaidi100.com/';
        $ch = curl_init($url);
        curl_setopt_array($ch,$options);
        $html = curl_exec($ch);
        curl_close($ch);
        return $html;
    }

    public function ping() {
        echo json_encode([
            'result' =>1
        ]);
    }
}